import React, { useEffect, useState } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';

import Cloud from 'leancloud-storage'

const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
};
const beforeUpload = (file) => {
  const typeList = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif', 'image/bmp', 'image/webp', 'image/svg+xml']; // 图片格式
  const isJpgOrPng =  typeList.includes(file.type) ;
  if (!isJpgOrPng) {
    message.error('上传图片的格式不正确!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('上传图片大小不超过2MB!');
  }
  return isJpgOrPng && isLt2M;
};
const ImageUpload = (props) => {
  const {defaultUrl} = props
  useEffect(() => {
    if (defaultUrl) {
      setImageUrl(defaultUrl);
    }
  }, [defaultUrl]);
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState();
  const handleCustomRequest = (info) => {
    setLoading(true);
    getBase64(info.file, (base64) => {
      const file = new Cloud.File('cakeimg.png', {base64}); //将本地资源转化为一个可以向leancloud平台提交的资源
      file.save().then((res) => {
        // 将图片的url传递给父组件
        props.onChange(res?.attributes.url);
        setLoading(false);
        setImageUrl(res?.attributes.url);
      })
    });
  }
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </div>
  );
  return (
    <>
      <Upload
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        beforeUpload={beforeUpload}
        customRequest={handleCustomRequest}
      >
        {imageUrl ? (
          <img
            src={imageUrl}
            alt="avatar"
            style={{
              width: '100%',
            }}
          />
        ) : (
          uploadButton
        )}
      </Upload>
    </>
  );
};
export default ImageUpload